package com.zirenx.common.controller;

import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.upload.UploadFile;
import com.zirenx.annotation.RouteMapping;
import com.zirenx.common.config.ConstantConfig;
import com.zirenx.sys.model.SysFile;
import com.zirenx.sys.service.SysFileService;
import com.zirenx.utils.FileUtils;
import com.zirenx.utils.LogUtils;
import com.zirenx.utils.R;
import com.zirenx.utils.SysUserUtils;

/**
 * 富文本文件上传
 */
@RouteMapping("/ueditor")
public class UeditorController extends Controller {

    @Inject
    SysFileService sysFileService;

    public void upload(){
        R r = R.ok();
        UploadFile uploadFile = null;
        try {
            uploadFile = getFile("upfile");
            SysFile sysFile = sysFileService.saveFile(uploadFile.getFileName(), "富文本文件上传");
            byte[] bytes = FileUtils.getBytesByFile(uploadFile.getFile());
            FileUtils.uploadFile(bytes, ConstantConfig.UPLOAD_PATH + sysFile.getUrl());

            r.put("original",uploadFile.getFileName());
            r.put("title",uploadFile.getFileName());
            r.put("url",getRequest().getContextPath() + sysFile.getUrl());
            r.put("type",FileUtils.fileType(uploadFile.getFileName()));
            r.put("state","SUCCESS");
        } catch (Exception e) {
            LogUtils.error(this.getClass(),e);
            r = R.error();
            r.put("state","FAIL");
        }
        if(uploadFile!=null) {
            uploadFile.getFile().delete();	//删除临时文件
        }
        renderJson(r);
    }


}
